<template>
  <div :class='s.wrap' ref='wrap' :style='{height: screenH + "px"}'>
    <!-- <action-bar
      title='评论'
      color='#000'
      :class='s.actionBar'>
      <template slot='left'>
        <action-button color='#ddd' @click='onBack'>
          <img src="~assets/images/return.png" :class='s.icon'>
        </action-button>
      </template>
      <template slot='right'>
        <action-button color='transparent'>
        </action-button>
      </template>
    </action-bar> -->
    <div :class='s.msgs'
      ref='msgs'
      @touchstart='onTouchStart'
      @touchmove='onTouchMove'
      @touchend='onTouchEnd'>
      <div :class='s.tip' v-if='isLoading'>加载中...</div>
      <div :class='s.tip' v-if=' msgs.length === 0'>没有评论，快来抢沙发</div>
      <template v-if='!isLoading'>
        <div :class='s.tip' v-if='hasMoreComments && !isLoading'>下拉加载更多</div>
        <div :class='s.tip' v-else-if=' msgs.length > 0'>登顶评论巅峰啦，没有更多了</div>
      </template>
      <template
        v-for='msg in msgs'>
        <msg-item 
          :msgProps='msg'
          :key='msg.SERIAL_NO'>
        </msg-item>
      </template>
      <template>
        <div :class='s.tip' v-if='isLoadingNews'>加载中...</div>
        <div :class='s.tip' v-if='!showNoNew && !isLoadingNews && msgs.length > 0'>上拉加载新消息</div>
        <div :class='s.tip' v-if='!isLoadingNews && showNoNew'>暂无新评论</div>
      </template>
    </div>
  </div>
</template>

<script>
// import ActionBar from 'components/actionBar'
// import ActionButton from 'components/actionBar/ActionButton'
import MsgItem from 'components/comment/MsgItem'
import RemoteDAO from 'common/RemoteDAO'
export default {
  components: { MsgItem },
  data () {
    return {
      msgs: [{}, {}, {}, {}, {}, {}, {}, {}],
      screenH: 0,
      params: {
        PAGE_SIZE: 20,
        PAGE_NO: 1,
        ID: '',
        QUERY_FLAG: 0
      },
      isInit: true,
      isLoading: false,
      isLoadingNews: false,
      hasNewComments: false,
      hasMoreComments: true,
      showNoNew: false,
      noNewTimer: null,
      touchData: {
        isMoving: false,
        startY: 0,
        endY: 0,
        scrollPos: 0,
        marginTop: -60,
        marginBottom: -60,
        distance: 0
      }
    }
  },
  mounted () {
    this.screenH = window.innerHeight
    this.params.ID = this.$route.query.id
    this.fetchComments(this.params, false)
  },
  updated () {
    this.screenH = window.innerHeight
  },
  methods: {
    onTouchStart (evt) {
      console.info('onTouchStart', evt)
      this.touchData.isMoving = false
      if (evt.changedTouches.length <= 0) return
      this.touchData.startY = evt.changedTouches[0].pageY
    },
    onTouchMove (evt) {
      console.info('onTouchMove', evt)
      this.touchData.isMoving = true
      // 移动列表
      var distance = evt.changedTouches[0].pageY - this.touchData.startY
      console.info('onTouchMove', distance)
      if (distance < 0 && distance >= -80 && this.atBottom()) this.touchData.marginBottom = -60 - distance
      else if (distance <= 80 && distance >= 0 && this.atTop()) this.touchData.marginTop = -60 + distance
    },
    onTouchEnd (evt) {
      console.info('onTouchEnd', evt)
      this.touchData.marginTop = -60
      this.touchData.marginBottom = -60
      if (evt.changedTouches.length <= 0 || !this.touchData.isMoving) return
      this.touchData.endY = evt.changedTouches[0].pageY
      if ((this.touchData.startY - this.touchData.endY) >= 0) this.fetchNewComments() // 用户向上拉
      else this.fetchOldComments()
      // reset touch data
      this.touchData.startY = 0
      this.isMoving = false
    },
    noNewMsgs () {
      this.showNoNew = true
      if (this.noNewTimer != null) {
        clearTimeout(this.noNewTimer)
        this.noNewTimer = null
      }
      this.noNewTimer = setTimeout(() => {
        this.showNoNew = false
      }, 500)
    },
    onBack () {
      this.$router.go(-1)
    },
    /**
     * 加载最新评论
     */
    fetchNewComments () {
      if (this.atBottom()) {
        console.info('fetchNewComments')
        this.isLoadingNews = true
        var params = {
          PAGE_SIZE: 20,
          PAGE_NO: 1,
          ID: this.params.ID,
          QUERY_FLAG: 0
        }
        this.fetchComments(params, true)
      }
    },
    fetchOldComments () {
      if (this.$refs.wrap.scrollTop <= 200 && this.hasMoreComments) {
        // 用户滑到顶部了
        this.touchData.scrollPos = this.$refs.wrap.scrollHeight - this.$refs.wrap.scrollTop
        this.isLoading = true
        this.params.PAGE_NO += 1
        this.fetchComments(this.params, false)
      }
    },
    fetchComments (params, isfetchNews) {
      console.info('params', params)
      RemoteDAO.callUC12008318(params).then(resp => {
        console.info('fetchComments', resp)
        if (!isfetchNews) this.unshiftMsgs(resp.data.body || []) // 获取历史评论
        else this.mergeNewComments(resp.data.body || []) // 合并新消息
      }).catch(err => {
        console.error('fetchComments', err)
      })
    },
    formatMsg (msg) {
      return msg
    },
    mergeNewComments (newMsgs) {
      var findPos = false
      var lastSerialNo // 已有评论列表中最新一条评论的序列号
      var msgs = []
      if (this.msgs.length <= 0 || !this.msgs[this.msgs.length - 1].SERIAL_NO) {
        findPos = true
      } else {
        lastSerialNo = this.msgs[this.msgs.length - 1].SERIAL_NO
      }
      for (let i = newMsgs.length - 1; i >= 0; i--) {
        if (findPos) {
          newMsgs[i] = this.formatMsg(newMsgs[i])
          msgs.push(newMsgs[i])
        } else {
          if (lastSerialNo === newMsgs[i].SERIAL_NO && i !== 0) findPos = true
        }
      }
      if (!findPos || msgs.length === 0) this.noNewMsgs()
      this.msgs = this.msgs.concat(msgs)
      this.isLoadingNews = false
    },
    unshiftMsgs (data) {
      if (data.length === 0) this.hasMoreComments = false
      var tempMsgs = []
      for (var i = 0; i < data.length; i++) {
        tempMsgs.unshift(data[i])
      }
      if (this.isInit) {
        this.isInit = false
        this.msgs = tempMsgs
        this.$nextTick(() => {
          this.scroll2Bottom()
          this.isLoading = false
        })
      } else {
        this.msgs = tempMsgs.concat(this.msgs)
        this.$nextTick(() => {
          this.$refs.wrap.scrollTop = this.$refs.wrap.scrollHeight - this.touchData.scrollPos
          this.isLoading = false
        })
      }
    },
    scroll2Bottom () {
      this.$refs.msgs.scrollTop = this.$refs.msgs.scrollHeight + 20
      // this.$refs.wrap.scrollTop = this.$refs.wrap.scrollHeight + 20
    },
    atBottom () {
      var divid = this.$refs.wrap.scrollHeight - (this.$refs.wrap.clientHeight + this.$refs.wrap.scrollTop)
      console.info('divid', divid)
      if (divid >= -1 && divid <= 1) return true
      return false
    },
    atTop () {
      if (this.$refs.wrap.scrollTop === 0) return true
      else return false
    }
  },
  beforeDestroy () {
    if (this.noNewTimer != null) {
      clearTimeout(this.noNewTimer)
      this.noNewTimer = null
    }
  }
}
</script>

<style lang="less" module='s'>
.wrap{
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}
.msgs{
  height: 100%;
  background-color: #f1f3f6;
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}
.tip{
  color: #999;
  text-align: center;
  font-size: 20px;
  margin: 35px auto;
}
.actionBar{
  box-shadow: 1px 0 1px 1px rgba(0,0,0,0.1);
  z-index: 2;
  background-color: #fff;
}
.icon{
  width: 50%;
}
</style>

